use std::error::Error;
use std::fmt;

#[derive(Debug, PartialEq)]
enum CustomError {
    ParseError(String),
    OverflowError(String),
}

impl fmt::Display for CustomError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::ParseError(msg) => write!(f, "Parse Error: {}", msg),
            Self::OverflowError(msg) => write!(f, "Overflow Error: {}", msg),
        }
    }
}

impl Error for CustomError {}

fn parse_then_log(s: &str) -> Result<u32, CustomError> { //String> {  
    //s.parse::<u32>()  
    //    .map_err(|e| format!("Parse error: {}", e))?  
    //    .checked_mul(2).ok_or("Overflow".to_string())  
    let num = s.parse::<u32>()
        .map_err(|_e| CustomError::ParseError(format!("'{}' is invalid input", s)))?;
    
    num.checked_mul(2)
        .ok_or_else(|| CustomError::OverflowError(format!("{} * 2 exceeds u32", num)))
}  

#[test] 
fn test_error_chain() { 
    /* 测试不同错误场景 */ 
    // 测试有效输入
    assert_eq!(parse_then_log("42"), Ok(84));
    
    // 测试解析错误
    assert!(matches!(parse_then_log("abc"), Err(CustomError::ParseError(_))));
    assert!(matches!(parse_then_log(""), Err(CustomError::ParseError(_))));
    
    // 测试溢出错误
    assert!(matches!(parse_then_log(&u32::MAX.to_string()), 
                    Err(CustomError::OverflowError(_))));
}  

// 添加错误处理演示
fn main() {
    let test_cases = ["123", "9999999999", "0x1f", "2147483648"];
    
    for input in test_cases {
        match parse_then_log(input) {
            Ok(val) => println!("✅ {} => {}", input, val),
            Err(e) => println!("❌ {}: {}", input, e),
        }
    }
}